
(function() {
	var a=YAHOO.util.Dom,b=YAHOO.util.Event;
	var FaceWindow = null;
	YAHOO.namespace("ChatXP.logic");
	YAHOO.ChatXP.logic.Client = {
		chat_proxy_uri: 'chatty',
		pm: null,
		transfer_table:[14,1,2,3,4,5,6,7,8,9,10,11,12,13,0,50,51,96,53,54,73,74,75,76,77,78,55,56,57,58,79,80,81,82,83,84,85,86,87,88,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,32,113,114,115,63,64,59,33,34,116,36,37,38,91,92,93,29,117,72,45,42,39,62,46,47,71,95,118,119,120,121,122,123,124,27,21,23,25,26,125,126,127,128,129,130,131,132,133,134,52,24,22,20,60,61,89,90,31,94,65,35,66,67,68,69,70,15,16,17,18,19,28,30,40,41,43,44,48,49],
		http_callback : {},
		init : function() {
			var me = this;
			this.face_domain = "/images/";
			
			//this._close_btn_ref2 = a.get("Talk_group0_close2");
			this._input_ref = a.get("Talk_group0_input");
			this._send_ref=a.get("Talk_group0_send");
			this._history_ref=a.get("Talk_group0_history");
			this._face_btn_ref = a.get("Talk_group0_face_tab");
			this._buddy_name_node = a.get("Talk_group0_title");
			
			this.web_session = g_session;
			this._buddy_name_node.innerHTML = g_admin.forHtml();
			
			var chatInput = this._input_ref.firstChild;
			chatInput.className = "textarea";
			chatInput.maxLength = 1024;

			b.on(chatInput, "keydown", this.mf_OnTextareaKey, this, true);			
			
			/*b.on(this._close_btn_ref2, "click", function() {
				if(confirm("确认要关闭聊天窗口么？")) {
					window.close();
				}
			},this, true);*/
			b.on(this._send_ref,"click",this.mf_OnSend,this,true);
			b.on(this._face_btn_ref,"click",this.mf_PopUpFaceWindow,this,true);		
			//alert("begin to send pack looply");
			this.http_callback = {				
				onSuccess : me.recvMsgCallback,
				onFailure : me.recvMsgCallback,
				timeout : 30000,
				scope : me
			};
			//alert("set the get message looply");
			this.pm = Transport;
			this.pm.init(this);
			//窗口关闭事件,注销session
			b.on(window, "beforeunload", this.closeWinHook, this, true)
			
			this.pollMsg();
		},
		mf_OnTextareaKey:function(f) {
			var c = b.getCharCode(f);
			if (c == 13 && f.ctrlKey) {
				this.mf_OnSend(f);
			}
		},
		pollMsg : function() {
			//
			//alert("strat to send pollmsg");
			var body = "", pkg = new Package(g_uid, "00", this.pm.cs_seq++, g_session, body);
			this.pm.sendPackage(pkg);
			//
			//alert("wait for the server's response");
		
		},
		//假设服务端返回的数据格式是json转换后的字符串，移动端需要先进行转换为json对象数组
		//服务端返回的文本消息字符串格式务必如下：
	    /*[{"title":g_uid + "&nbsp;&nbsp;"+格式化管理员发送消息的时间字符串;,"content":格式化的管理员发送的消息内容
	    }]*/
		recvMsgCallback : function(o) {
			//响应异常或响应的数据包为空对象，跳过不做任何处理
			Transport.RELAY_TIME = 3000;
			if ((!o || (!o.responseText) || (o.responseText == "") || (o.responseText == "success")) && !this.isExit) {				
				this.pollMsg();
				return true;
			}
			//子函数调用，负责客户端把返回的文本消息转换为json消息对象数组并显示到历史列表里面
			//alert(this.pollMsg);
			this.pollMsg();			
			
			var pkgs;
			try {
				pkgs = YAHOO.lang.JSON.parse(o.responseText);
			} catch(e) {
				alert(e)
				return;
			}

			for ( var q = 0; q < pkgs.length; ++q) {
				var pkg = pkgs[q];
				var cmd = parseInt(pkg.cmd, 16), seq = Number(pkg.seq);
				var reqPkg = this.pm.removePackage(seq);
				if (reqPkg && reqPkg.option) {
					reqPkg.option.arguments.params = pkg;
					reqPkg.option.onSuccess.call(reqPkg.option.sscope, reqPkg.option.arguments);
				}

				var me = this;
				try {
					switch (cmd) {
						case 23:
							msg = pkg.body;
							var ctt = msg.content;
							ctt = ctt.escape2html();
							//TODO var M = String(msg);
							ctt = ctt.replace(/\x14(\d|[a-f]){2}/g, function(ai) {
								return '<img align="absmiddle" src=' + me.face_domain + "emotions/" + parseInt("0x" + ai.substr(1)) + ".gif>"
							});
							
							var msgDateStr = "";
							try {
								var msgDate = new Date();
								if (msg['timestamp']) {
									msgDate.setTime(parseInt(msg.timestamp) * 1000)
								}
								//ah = msgDateStr
								msgDateStr = msgDate.format("yyyy-MM-dd hh:mm:ss");
							} catch(e) {}
							
							var fmsg = {from: msg.sender, to: msg.to, title: msg.sender + " " + msgDateStr, content: ctt};
							this.mf_notify_recv(fmsg);
							break;
						break; default:
							YAHOO.log("unknown message: " + pkg);
							break
					}
				} catch (r) {}
			}
			
		
		},	
		mf_TranslateMessage:function(d){
			var me = this;
			var j="",e="";

			var k=function(i){
				var m=0;
				switch(String(i).toUpperCase()) {
					case"[/:)]":m=0;break;
					case"[/:~]":m=1;break;
					case"[/:B]":m=2;break;
					case"[/:|]":m=3;break;
					case"[/8-)]":m=4;break;
					case"[/:<]":
					case"[/:&LT;]":m=5;break;
					case"[/:$]":m=6;break;
					case"[/:X]":m=7;break;case"[/:Z]":m=8;break;
					case"[/:'(]":m=9;break;case"[/:-|]":m=10;break;
					case"[/:@]":m=11;break;case"[/:P]":m=12;break;
					case"[/:D]":m=13;break;case"[/:O]":m=14;break;
					case"[/:(]":m=15;break;case"[/:+]":m=16;break;
					case"[/--B]":m=17;break;case"[/:Q]":m=18;break;case"[/:T]":m=19;break;case"[/;P]":m=20;break;
					case"[/;-D]":m=21;break;case"[/;D]":m=22;break;case"[/;O]":m=23;break;case"[/:G]":m=24;break;case"[/|-)]":m=25;break;
					case"[/:!]":m=26;break;case"[/:L]":m=27;break;case"[/:>]":case"[/:&GT;]":m=28;break;case"[/:;]":m=29;break;
					case"[/;F]":m=30;break;case"[/:-S]":m=31;break;case"[/?]":m=32;break;case"[/;X]":m=33;break;case"[/;@]":m=34;break;
					case"[/:8]":m=35;break;case"[/;!]":m=36;break;case"[/!!!]":m=37;break;case"[/XX]":m=38;break;case"[/BYE]":m=39;break;
					case"[/WIPE]":m=40;break;case"[/DIG]":m=41;break;case"[/HANDCLAP]":m=42;break;case"[/&-(]":case"[/&AMP;-(]":m=43;break;
					case"[/B-)]":m=44;break;case"[/<@]":case"[/&LT;@]":m=45;break;case"[/@>]":case"[/@&GT;]":m=46;break;case"[/:-O]":m=47;break;
					case"[/>-|]":case"[/&GT;-|]":m=48;break;case"[/P-(]":m=49;break;case"[/:'|]":m=50;break;case"[/X-)]":m=51;break;
					case"[/:*]":m=52;break;case"[/@X]":m=53;break;
					case"[/8*]":m=54;break;case"[/PD]":m=55;break;
					case"[/<W>]":case"[/&LT;W&GT;]":m=56;break;case"[/BEER]":m=57;break;
					case"[/BASKETB]":m=58;break;case"[/OO]":m=59;break;case"[/COFFEE]":m=60;break;
					case"[/EAT]":m=61;break;case"[/PIG]":m=62;break;case"[/ROSE]":m=63;break;case"[/FADE]":m=64;break;
					case"[/SHOWLOVE]":m=65;break;case"[/HEART]":m=66;break;case"[/BREAK]":m=67;break;case"[/CAKE]":m=68;break;
					case"[/LI]":m=69;break;case"[/BOME]":m=70;break;case"[/KN]":m=71;break;case"[/FOOTB]":m=72;break;case"[/LADYBUG]":m=73;break;
					case"[/SHIT]":m=74;break;case"[/MOON]":m=75;break;case"[/SUN]":m=76;break;case"[/GIFT]":m=77;break;case"[/HUG]":m=78;break;
					case"[/STRONG]":m=79;break;case"[/WEAK]":m=80;break;case"[/SHARE]":m=81;break;case"[/V]":m=82;break;case"[/@)]":m=83;break;
					case"[/JJ]":m=84;break;case"[/@@]":m=85;break;case"[/BAD]":m=86;break;case"[/LOVEU]":m=87;break;case"[/NO]":m=88;break;
					case"[/OK]":m=89;break;case"[/LOVE]":m=90;break;case"[/<L>]":case"[/&LT;L&GT;]":m=91;break;case"[/JUMP]":m=92;break;
					case"[/SHAKE]":m=93;break;case"[/<O>]":case"[/&LT;O&GT;]":m=94;break;case"[/CIRCLE]":m=95;break;case"[/KOTOW]":m=96;break;
					case"[/TURN]":m=97;break;case"[/SKIP]":m=98;break;case"[/OY]":m=99;break;case"[/#-O]":m=100;break;case"[/HIPHOP]":m=101;break;
					case"[/KISS]":m=102;break;case"[/<&]":case"[/&LT;&AMP;]":m=103;break;case"[/&>]":case"[/&AMP;&GT;]":m=104;break;
					default:m=-1;break
				}
				return m
			};
			if(b.isIE) {
				for(var f=0;f<d.childNodes.length;f++){
					var c=d.childNodes[f];
					switch(c.nodeName.toUpperCase()){
						case"BR":
							e+="\n";j+="<br/>";break;
						case"#TEXT":
							j+=c.nodeValue.escape2html();
							e+=c.nodeValue;break;
						case"IMG":
							j+='<img src="'+c.src+'">';var h=c.src.search("emotions/")+String("emotions/").length;
							var g = parseInt(c.src.substr(h));
							if(!isNaN(g)){e+=("\x14"+g.toHex())}break;
						default:break
					}
				}
			} else {
				j=d.value.escape2html();
				e=d.value;
			}
			var l=this;
			j=j.replace(/\t/g,"&nbsp;");
			j=j.replace(/\[[^\]\n]{2,10}\]/g,function(i){
				var m=k(i);
				return(m<0)?i:('<img align="absmiddle" src="images/emotions/'+m+'.gif" />')
			});
			e=e.replace(/\t/g," ");
			e=e.replace(/\[[^\]\n]{2,9}\]/g,function(i){
				var m=k(i);
				return(m<0)?i:("\x14"+m.toHex());
			});
			return[j,e]
		},
		mf_PreventDefault:function(c){b.stopEvent(c)},
		mf_PopUpFaceWindow:function(){
			FaceWindow = YAHOO.ChatXP.ui.MainPanel.getInstance(this);
			FaceWindow.mf_ShowFace("Talk_group0_face_tab");
		},
		mf_OnSend:function(r) {
			//alert("begin to send:step1");
			b.preventDefault(r);

			var input = this._input_ref.firstChild;
			h=this.mf_TranslateMessage(input);

		    //alert("s:"+h[0]+" p"+h[1]);
			var s=h[0],p=h[1];
			if(p==""){
				alert("发送内容不能为空，请重新输入！");return
			} else {
				if(p.length>400){
					alert("对不起，您输入的内容过长！");
					return
				}
			}
			//alert("begin to send:step2");	
			var d=new Date();
			var j=d.getFullYear(),m=d.getMonth()+1,n=d.getDate(),i=d.getHours(),l=d.getMinutes(),t=d.getSeconds();
			var f=(d.getFullYear()+"-"+((m>9)?m:"0"+m)+"-"+((n>9)?n:"0"+n)+"&nbsp;"+((i>9)?i:"0"+i)+":"+((l>9)?l:"0"+l)+":"+((t>9)?t:"0"+t));
			var c = g_uid + "&nbsp;&nbsp;"+f;
			//alert("from:"+g_uid+"to:"+g_admin+"content:"+encodeURIComponent(p));
			
			//需要相关模块定义一个新的字段，把管理员名字加入
			
			//var pack_msg = {from:g_uid,to:g_admin,content: encodeURIComponent(p)};
			//this.send_msg({from:g_uid,to:g_admin,content: encodeURIComponent(p)});
			//this.send_msg(pack_msg);
			/*alert("hello");
			alert(g_admin);
			*/
			//g_admin为对端id，g_uid为本端id
			this.sendC2CMsg(g_admin,"",encodeURIComponent(p),"16");
			var msg = {from: g_uid, to: g_admin, title: c, content: s};
			this.mf_notify_recv(msg);
			
			input.value = "";
		},
		sendC2CMsg : function(l, m, o,opr) {
			var j = this, n = {
				onSuccess :  function() {
				
			    },
				onFail : function() {
					
				},
				sscope : j,
				fscope : j,
				arguments : {},
				cmd : opr,
				timeout : 6,
				body : YAHOO.lang.JSON.stringify({'to':l,'face':m,'msg':o})
			};
			var k = this.getCmdInfo(n);
			return this.pm.cs_seq + 1000000;
		}, 
		getCmdInfo : function(r) {
			if (Object.prototype.toString.apply(r) != "[object Array]") {
				r = [ r ]
			}
			var p = [];
			for ( var l = 0; l < r.length; l++) {
				var j = r[l], k = j.cmd, m = j.body, q = j.reply_seq, s = (k == "22") ? 0 : (q || this.pm.cs_seq++), n = new Package(g_uid, k, s, this.web_session, m);
				n.setSendTime(new Date().getTime());
				n.setOption(j);
				p.push(s);
			    this.pm.sendPackage(n);
			}
			return p;
		},
		//历史列表更新函数，参数为Array数组
		mf_notify_recv:function(msg) {
			var o,p,f;
			//用层的方式显示发送或接受列表
			if(!msg) return;	

			o=document.createElement("div");
			p=document.createElement("p");
			p.className = "my-id";
			p.innerHTML = msg.title;
			o.appendChild(p);

			f=document.createElement("P");
			f.className="content";
			f.innerHTML=msg.content;
			o.appendChild(f);
			this._history_ref.appendChild(o);
		
			
			var me=this;
			window.setTimeout(function(){
				me.mf_SyncHistoryScroll()
			},0);
		},
		mf_SyncHistoryScroll: function(){
			this._history_ref.scrollTop=this._history_ref.scrollHeight;
		},
		closeWinHook : function(k) {
			//YAHOO.util.Cookie.remove("chatty", { domain: "chattyc2b.appspot.com" }); 
			var cookieFrm = document.createElement("iframe");
			cookieFrm.src = "http://127.0.0.1:8080/js/ccc.html";
			document.body.appendChild(cookieFrm);
			
			var me = this, 
			pkg = {
				onSuccess : function() {
				},
				onFail : function() {
				},
				sscope : me,
				fscope : me,
				arguments : {},
				cmd : "1234",
				body : this.web_session
			};
			
			
			
			this.getCmdInfo(pkg);
			
			var j = "退出后本次聊天的所有信息将不被保留，是否确认退出？";
			if (YAHOO.util.Event.isSafari) {
				return j
			}
			k = YAHOO.util.Event.getEvent(k);
			k.returnValue = j
		}
	};
	
	

	b.onDOMReady(function () {
		YAHOO.ChatXP.logic.Client.init();
	});
})();